package com.joinway.framework.support.sso;

import java.util.Date;
import java.util.UUID;

import org.springframework.cache.Cache;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.cache.CacheManager;

import com.joinway.framework.bean.sso.SSOContext;
import com.joinway.framework.bean.sso.constant.SSOConstants;

public abstract class SingleSignOnServiceAdaptor<T extends SSOContext> implements ISingleSignOnService<T> {

	protected CacheManager cacheManager;
	
	/**
	 * sso token live seconds
	 */
	protected int liveSeconds = 300;
	
	@Override
	public String createToken(T context) {
		String token = UUID.randomUUID().toString();
		
		Date now = new Date();
		
		context.setCreateTime(now);
		context.setUpdateTime(now);
		
		Cache cache = cacheManager.getCache(SSOConstants.SSO_CACHE_NAME);
		cache.put(token, context);
		
		return token;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T getSSOContext(String token) {
		Cache cache = cacheManager.getCache(SSOConstants.SSO_CACHE_NAME);
		
		ValueWrapper wrapper = cache.get(token);
		T context = (T)wrapper.get();
		
		if(liveSeconds > 0){
			Date now = new Date();
			int delt = (int)(now.getTime() - context.getUpdateTime().getTime());
			if(delt / 1000 > liveSeconds){
				// token was expired
				context = null;
				cache.evict(token);
			}
		}
		
		return context;
	}
	
	@Override
	public void saveSSOContext(String token, T context) {
		T ctx = getSSOContext(token);
		
		if(ctx != null){
			context.setUpdateTime(new Date());
		}else{
			Date now = new Date();
			context.setCreateTime(now);
			context.setUpdateTime(now);
		}
		
		Cache cache = cacheManager.getCache(SSOConstants.SSO_CACHE_NAME);
		cache.put(token, context);
	}

	public CacheManager getCacheManager() {
		return cacheManager;
	}

	public void setCacheManager(CacheManager cacheManager) {
		this.cacheManager = cacheManager;
	}

	public int getLiveSeconds() {
		return liveSeconds;
	}

	public void setLiveSeconds(int liveSeconds) {
		this.liveSeconds = liveSeconds;
	}

}
